package com.gutsyzhan.dynamicdatasourcespringbootstarter.creator;

import com.gutsyzhan.dynamicdatasourcespringbootstarter.init.DataSourceInit;
import com.gutsyzhan.dynamicdatasourcespringbootstarter.properties.DataSourceProperty;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public abstract class AbstractDataSourceCreator implements DataSourceCreator{
    @Setter(onMethod = @__({@Autowired}))
    private List<DataSourceInit> dataSourceInits;

    @Override
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        //数据源创建之前干预
        Optional.ofNullable(dataSourceInits).stream().flatMap(Collection::stream).sorted(
                Comparator.comparing(DataSourceInit::getOrder))
                .forEach(init -> init.beforeCreate(dataSourceProperty));

        DataSource dataSource = doCreateDataSource(dataSourceProperty);

        //数据源创建之后干预
        Optional.ofNullable(dataSourceInits).stream().flatMap(Collection::stream).sorted(
                Comparator.comparing(DataSourceInit::getOrder))
                    .forEach(init -> init.afterCreate(dataSourceProperty));
        return dataSource;
    }

    protected abstract DataSource doCreateDataSource(DataSourceProperty dataSourceProperty);
}
